package com.gu.myviewmodel.repo

import android.util.Log
import com.gu.myviewmodel.services.Car
import dagger.hilt.android.scopes.ViewModelScoped
import javax.inject.Inject

@ViewModelScoped
class Repo @Inject constructor(private val dataBase: DataBaseRepo, private val remoteRepo: RemoteRepo) : BaseRepo<Car>() {
    private val data = mutableListOf<Car>()
    private var needRefreshData = false

    override suspend fun loadData(): List<Car> {
        if (needRefreshData) {
            log("强制刷新")
            needRefreshData = false
            clear()
            initLoad()
        } else if (isEmpty()) {
            if (!dataBase.isEmpty()) {
                log("从数据库加载")
                val res = dataBase.loadData()
                addAll(res)
            } else {
                initLoad()
            }
        } else {
            log("直接从内存加载")
        }
        return mutableListOf<Car>().also { it.addAll(data) }
    }

    override suspend fun isEmpty(): Boolean {
        return data.isEmpty()
    }

    override suspend fun clear() {
        data.clear()
    }

    fun changeRefreshFlag() {
        needRefreshData = true
    }

    private fun addAll(list: List<Car>) {
        data.addAll(list)
    }

    private suspend fun initLoad() {
        log("从网络获取")
        val res = remoteRepo.loadData()
        dataBase.clear()
        if (res.isNotEmpty()) {
            dataBase.insert(res)
            addAll(res)
        }
        needRefreshData = false
    }

    override fun repoTag() = "Repo"

}


abstract class BaseRepo<T> {
    abstract suspend fun loadData(): List<T>?
    abstract suspend fun isEmpty(): Boolean
    abstract suspend fun clear()
    abstract fun repoTag(): String

    fun log(str: String) {
        Log.e(repoTag(), "----$str---- ")
    }
}